package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("order")
public class OderController {

    @Reference
    OrderService orderService;

    @Autowired
    private  JedisPool jedisPool;

    @RequestMapping("submit")
    public Result submit(@RequestBody Map map) throws Exception {


        String telephone = (String) map.get("telephone");
        String key = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

        String validateCode = (String) map.get("validateCode");

        if (key.equals(validateCode)){

            Result result = orderService.order(map);

            if (result.isFlag()){
                //预约成功
                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,map.get("orderDate").toString());
            }

            return  result;
        }else {
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }


    }


    @RequestMapping("findById")
    public Result findById(int id) {
        try {
            Map map= orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
